package httpserver;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;

/**
 * Shutdown class to the Server. This is used for the stopping thread to ensure gracefull shutdown 
 * @version 1.0
 * @author Casper, Jackie, Jacob og Dennis.
 */
public class Shutdown implements Runnable {
    private ConfigHandler cfg;
    private ServerSocket shutdownSocket;
    private Server server;
/**
 *
 * @param server the server that is parsed, which is wanted to be shut down.
 * @throws IOException
 */
    public Shutdown(Server server) throws IOException{
        cfg = new ConfigHandler();
        this.server = server;
        shutdownSocket = new ServerSocket(cfg.getShutdownPort());
    }
/**
 * Abstract method implementation from the interface runnable, to enable the<br>
 * class to run in a Thread. The method accepts a connection on the given port<br>
 * and sends a confirmation to the client. Afterwards it sets the boolean running<br>
 * on server to false and sets the socket timeout to the given amount of milliseconds.
 */
    public void run() {
        Server.LOGGER.info("Shutdown socket created - listening on port: "+cfg.getShutdownPort());
            try {
                Socket shutdownSock = shutdownSocket.accept();
                server.setRunning(false);
                
                String header = "HTTP/1.0 200 OK\r\n\r\n";
                String html = "<html>" +
                        "<head><title>Server shutting down</title>" +
                        "</head>" +
                        "<body>The server is currently on a shutting down routine</body>" +
                        "</html>";

                OutputStream os = shutdownSock.getOutputStream();
                os.write(header.getBytes(),0,header.length());
//                os.write(html.getBytes(),0,html.length());
                os.flush();
                os.close();
                server.setSocketTimeout(500);
                shutdownSock.close();

                Socket finalSock = new Socket("localhost",cfg.getPort());
                String request = "GET index.html HTTP/1.0";
                OutputStream finalOs = finalSock.getOutputStream();
                finalOs.write(request.getBytes());
                finalOs.flush();
                finalOs.close();
                
            } catch (IOException ex) {
                Server.LOGGER.log(Level.WARNING, "IO exception on shutdown", ex);
            }
    }
}
